/**
 * author:Administrator
 * date:2016/3/2
 * desc:TODO
 */
"use strict";

let Router = require('koa-router')
  , __pathPrefix = '/api/v1/category'
  , router = new Router({prefix: __pathPrefix});
module.exports = router.routes();
console.log('router:' + __pathPrefix + ',file=' + __filename);

let appUtil = require('../../common/appUtil.js');
let koabody = require('koa-better-body')();
let FormatOutput = require('../../common/FormatOutput.js');
let FormatError = require('../../common/FormatError.js');
let platformService = require('../../service/platform');

/**
 * get category
 * get /api/v1/category         ==> 获取所有
 * get /api/v1/category?top=1   ==> 顶层
 * get /api/v1/category?pid=3   ==> 某个节点下所有child
 */
router.get('/', koabody, function*() {
  let top = this.query.top;
  let qs = {};
  if (!!top) qs.top = top;

  let pid = this.query.pid;
  if (!!pid)  qs.pid = pid;

  let resVal = yield platformService.category(qs);
  this.body = FormatOutput.payloadOrError(resVal, FormatError.E_category_query);

});


/**
 * create category
 * post /api/v1/category
 * {name,pid}
 */
router.post('/', koabody, function*() {
  let user = yield appUtil.getUser(this);
  if (!user) return this.body = FormatOutput.payloadOrError(null, FormatError.E_need_login);
  if (!user.role || user.role.type != 'manager') {
    return this.body = FormatOutput.payloadOrError(null, FormatError.E_permission_deny);
  }

  let fields = this.request.body.fields;
  let name = fields.name;
  let pid = fields.pid;
  let resVal = yield platformService.createCategory(name, pid);
  this.body = FormatOutput.payloadOrError(resVal, FormatError.E_category_create);
});